package com.husd.framework.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import javax.xml.stream.XMLStreamException;
import java.io.IOException;

/**
 * xml和java bean的转换
 **/
public class XmlUtil {
    public static final XmlMapper xmlMapper;

    static {
        xmlMapper = new XmlMapper();
        //xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String toXml(Object object) throws JsonProcessingException {
        String s = xmlMapper.writeValueAsString(object);
        return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + s;
    }

    public static <T> T xmlToObject(String xml, Class<T> clazz) throws
            IOException, XMLStreamException {
        xmlMapper.setDefaultUseWrapper(false);
        /* 字段为null，自动忽略，不再序列化 */
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        /* 设置转换模式 */
        xmlMapper.enable(MapperFeature.USE_STD_BEAN_NAMING);
        return xmlMapper.readValue(xml, clazz);
    }
}
